<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="devName">
        <el-input v-model="queryParams.devName" placeholder="请输入设备名称" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:sunnylight:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:sunnylight:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:sunnylight:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
<el-button id="openbtn" type="success" :plain="selectedRows.length === 0" size="mini" :disabled="selectedRows.length === 0" @click="handleTurnOn(selectedRows)">
          <i class="el-icon-video-play" style="font-size: 1.3em; margin-right: 6px;"/>开启</el-button>
<el-button id="closebtn" type="danger" :plain="selectedRows.length === 0" size="mini" :disabled="selectedRows.length === 0" @click="handleTurnOff(selectedRows)">
          <i class="el-icon-video-pause" style="font-size: 1.3em; margin-right: 6px;"/>关闭</el-button>
      </el-col>
    <el-col :span="1.5">
    <el-button type="primary" plain icon="el-icon-time" size="small" @click="openDialog"
      :disabled="selectedRows.length===0" :class="{'plain-button':selectedRows.length===0}">参数配置</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <el-table v-loading="loading" :data="sunlightList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户" align="center" prop="nickName" width="155" show-overflow-tooltip/>
      <el-table-column label="项目" align="center" prop="projectname" width="155" show-overflow-tooltip/>
      <el-table-column label="设备编号" align="center" prop="id"/>
      <el-table-column label="设备名称" align="center" prop="devName" />
      <el-table-column label="IP地址" align="center" prop="ipAddress" />
      <el-table-column label="端口号" align="center" prop="portNo" />
      <el-table-column label="在线状态" align="center" width="86">
        <template slot-scope="scope">
          <div class="status-container"><img :src="getStateImags(scope.row.state)" alt="在线状态" style="width:22px;height:22px;"/></div>
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center">
        <template slot-scope="scope">
          <div class="status-container"><img :src="getStatusImage(scope.row.lightStatus)" alt="工作状态" style="width:22px;height:22px;"/></div>
        </template>
      </el-table-column>
      <el-table-column label="参数设置" align="center" prop="content">
        <template slot-scope="scope">
          <img v-if="cronBoxNoList.includes(scope.row.id+'')" :src="require(`@/assets/bigScreen/img/localStrategy.png`)"
            style="width:18px;height:auto;cursor:pointer;" @click="openStrategyDialog(scope.row)" v-hasPermi="['iot:cron:edit']"/>
  <span v-else style="color:#f56c6c;font-weight:bold;background-color:#fff4f4;padding:2px 6px;border-radius:4px;font-size:14px;">未定时</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:sunnylight:edit']">修改</el-button>
<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:sunnylight:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
<el-dialog title="参数设置" :visible.sync="dialogVisible" width="30%" class="strategy-dialog">
    <el-form :model="form" class="strategy-form">
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略1</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTime" :max="120" placeholder="一段时间(单位:分钟)" field="startTime"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTime" :max="900" placeholder="一段电流(单位:毫安)" field="endTime"/></el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略2</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTimeTwo" :max="120" field="startTimeTwo" placeholder="二段时间(单位:分钟)"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTimeTwo" :max="600" field="endTimeTwo" placeholder="二段电流(单位:毫安)"/></el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略3</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTimeThree" :max="120" field="startTimeThree" placeholder="三段时间(单位:分钟)"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTimeThree" :max="450" field="endTimeThree" placeholder="三段电流(单位:毫安)"/></el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略4</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTimeFour" :max="120" field="startTimeFour" placeholder="四段时间(单位:分钟)"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTimeFour" :max="300" field="endTimeFour" placeholder="四段电流(单位:毫安)"/></el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible=false">取 消</el-button><el-button type="primary" @click="handleSubmitForStrategys">确 定</el-button>
    </span>
  </el-dialog>
<el-dialog title="参数设置详情" :visible.sync="dialogVisibleForStrategy" width="30%" :show-close="false">
  <el-form ref="form" :model="form" label-width="58px">
      <el-form-item label="设备号:" prop="boxNo"><span style="font-size:16px;">{{this.form.boxNo}}</span></el-form-item>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略1</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTime" :max="120" placeholder="一段时间(单位:分钟)" field="startTime" @change="handleEndTimeChange" show-unit="分钟"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTime" :max="900" placeholder="一段电流(单位:毫安)" field="endTime" @change="handleEndTimeChange" show-unit="毫安"/></el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略2</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTimeTwo" :max="120" field="startTimeTwo" placeholder="二段时间(单位:分钟)" @change="handleEndTimeChange" show-unit="分钟"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTimeTwo" :max="600" field="endTimeTwo" placeholder="二段电流(单位:毫安)" @change="handleEndTimeChange" show-unit="毫安"/></el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略3</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTimeThree" :max="120" field="startTimeThree" placeholder="三段时间(单位:分钟)" @change="handleEndTimeChange" show-unit="分钟"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTimeThree" :max="450" field="endTimeThree" placeholder="三段电流(单位:毫安)" @change="handleEndTimeChange" show-unit="毫安"/></el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="strategy-section">
        <div class="strategy-header"><span class="strategy-title">策略4</span></div>
        <el-row :gutter="15" class="strategy-inputs">
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.startTimeFour" :max="120" field="startTimeFour" placeholder="四段时间(单位:分钟)" @change="handleEndTimeChange" show-unit="分钟"/></el-form-item>
          </el-col>
          <el-col :span="12">
<el-form-item class="custom-form-item"><number-picker v-model="form.endTimeFour" :max="300" field="endTimeFour" placeholder="四段电流(单位:毫安)" @change="handleEndTimeChange" show-unit="毫安"/></el-form-item>
          </el-col>
        </el-row>
      </div>
  </el-form>
      <span slot="footer" class="dialog-footer">
<el-button @click="cancelForDetail">取 消</el-button><el-button type="primary" @click="handleSubmitForDetail">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户名称" filterable style="width:100%" @change="handleNicknameChange">
            <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目名称" filterable style="width:100%" @change="handleProjectnameChange">
            <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="devName">
          <el-input v-model="form.devName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口号" prop="portNo">
          <el-input v-model="form.portNo" placeholder="请输入端口号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addCron, listCron, updateCron, updateCronBoxNo } from '@/api/iot/fahgboxcron'
import NumberPicker from './NumberPicker.vue';
import { listSunlight, getSunlight, delSunlight, addSunlight, updateSunlight } from "@/api/iot/sunlight";
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
import request from '@/utils/request'
export default {
  name: "Sunlight",
  components:{NumberPicker},
  data() {
    return {
      dialogVisibleForStrategy: false,
      cronBoxNoList: [],
      cronList: [],
      dialogVisible: false,
      pollInterval: null,
      options: [],
      projectnameOptions: [],
      selectedRows: [],
      pageSizes: [10,20,30,50],
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 慧光智慧太阳能灯表格数据
      sunlightList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        provideType: '4',
        adminId: null,
        customerId: null,
        projectId: null,
        devName: null,
        ipAddress: null,
        portNo: null,
        lightStatus: null,
        lightAdjustLevel: null,
        lightVolt: null,
        lightCurrent: null,
        activePower: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerId: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        projectId: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        devName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
        ipAddress: [{ required: true, message: "IP地址不能为空", trigger: "blur" }],
        portNo: [{ required: true, message: "端口号不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
    this.fetchCronBoxNoList();
    this.startPolling(); // 开始轮询
  },
  beforeDestroy() {
    clearInterval(this.pollInterval);
  },
  methods: {
    handleSubmitForDetail() {
      const updatedCronData = [];
      if (this.modifiedForm.startTime) {updatedCronData.push({ oneTime: this.form.startTime });}
      if (this.modifiedForm.endTime) {updatedCronData.push({ oneCurrent: this.form.endTime });}
      if (this.modifiedForm.startTimeTwo) {updatedCronData.push({ twoTime: this.form.startTimeTwo });}
      if (this.modifiedForm.endTimeTwo) {updatedCronData.push({ twoCurrent: this.form.endTimeTwo });}
      if (this.modifiedForm.startTimeThree) {updatedCronData.push({ threeTime: this.form.startTimeThree });}
      if (this.modifiedForm.endTimeThree) {updatedCronData.push({ threeCurrent: this.form.endTimeThree });}
      if (this.modifiedForm.startTimeFour) {updatedCronData.push({ fourTime: this.form.startTimeFour });}
      if (this.modifiedForm.endTimeFour) {updatedCronData.push({ fourCurrent: this.form.endTimeFour });}
      const updatedCron = {
        id: this.form.id,
        boxNo: this.form.boxNo,
        provideType: this.form.provideType,
        ...updatedCronData.reduce((acc,curr)=>({...acc,...curr}),{})
      };
      console.log('更新updatedCron数据:', updatedCron);
      updateCron(updatedCron).then(response => {
          this.$modal.msgSuccess("定时策略更新成功");
          this.dialogVisibleForStrategy = false;
        }).catch(error => {
          console.error('更新错误:', error);
          this.$modal.msgError("操作失败: 请求错误");
        });
    },
    handleEndTimeChange(field) {
      this.modifiedForm[field] = true;
      console.log('field:', field);
      console.log('this.modifiedForm数据:', this.modifiedForm);
    },
    openStrategyDialog(row) {
      listCron({boxNo:row.id}).then(response => {
          if (!response || typeof response !== 'object' || !Array.isArray(response.rows)) {
            console.error('响应格式不正确:', response);
            this.$message.error('响应格式不正确');
            return;
          }
          const cron = response.rows[0] || {};
          this.form = {
            startTime: cron.oneTime,
            endTime: cron.oneCurrent,
            boxNo: cron.boxNo,
            provideType: cron.provideType,
            id: row.id,
            startTimeTwo: cron.twoTime,
            endTimeTwo: cron.twoCurrent,
            startTimeThree: cron.threeTime,
            endTimeThree: cron.threeCurrent,
            startTimeFour: cron.fourTime,
            endTimeFour: cron.fourCurrent,
          };
          this.modifiedForm = {
            startTime: false,
            endTime: false,
            startTimeTwo: false,
            endTimeTwo: false,
            startTimeThree: false,
            endTimeThree: false,
            startTimeFour: false,
            endTimeFour: false,
          };
          this.dialogVisibleForStrategy = true;}).catch(error => {
          console.error('获取参数配置详情失败:', error);
          this.$message.error('获取参数配置详情失败');});},
    fetchCronBoxNoList() {
      this.loading = true;
      listCron(this.queryParams).then(response => {
        this.cronList = response.rows;
        this.cronBoxNoList = this.cronList.map(item => item.boxNo);
        console.log('cronBoxNoList:', this.cronBoxNoList);
        this.loading = false;
      }).catch(error => {
        console.error("获取参数配置列表失败:", error);
        this.loading = false;
      });
    },
    checkDeviceHasCron(boxNo){
      return new Promise((resolve,reject)=>{
        // 请求列表检查设备是否已有参数配置
        listCron({boxNo}).then(response=>{
            // 如果返回的rows数组非空，说明设备已有参数配置
            resolve(!!response.rows.length);
        }).catch(error=>{
            // 请求失败时返回错误信息
            reject(error);
        });
      });
    },
    handleSubmitForStrategys(){
      if(this.selectedRows.length===0){this.$message.warning('请选择设备');return;}
      const ipAddresss=this.selectedRows.map(row=>row.ipAddress);
      const portNos=this.selectedRows.map(row=>row.portNo);
      const idss=this.selectedRows.map(row=>row.id);
      console.log('idss的数据:',idss);
      //const provideTypes=this.selectedRows.map(row=>row.dsType);
      //const selectedBoxNos=new Set(this.selectedRows.map(row=>row.dsId));
      const cronData = {
        oneTime: this.form.startTime,
        oneCurrent: this.form.endTime,
        twoTime: this.form.startTimeTwo,
        twoCurrent: this.form.endTimeTwo,
        threeTime: this.form.startTimeThree,
        threeCurrent: this.form.endTimeThree,
        fourTime: this.form.startTimeFour,
        fourCurrent: this.form.endTimeFour,
      };
      console.log('cronData的数据:',cronData);
      const strategies=[
        {start:cronData.oneTime,end:cronData.oneCurrent},
        {start:cronData.twoTime,end:cronData.twoCurrent},
        {start:cronData.threeTime,end:cronData.threeCurrent},
        {start:cronData.fourTime,end:cronData.fourCurrent},];
      if(!strategies.some(strategy=>strategy.start&&strategy.end)){this.$message.warning('请至少填写一个参数配置');return;}
      //const checkPromises = [...selectedBoxNos].map(dsId=>this.checkDeviceHasCron(dsId));
      const checkPromises = [...idss].map(id=>this.checkDeviceHasCron(id));
      Promise.all(checkPromises).then(results => {
          results.forEach((deviceExists, index) => {
            const ipAddress = [...ipAddresss][index];
            const portNo = [...portNos][index];
            const id = [...idss][index];
            const boxNo = id;
            //const boxNo = [...selectedBoxNos][index];
            const provideType = '4';
            if(!deviceExists){//如果设备没有参数配置，则添加参数配置
              this.addDeviceAndCron(id, boxNo,ipAddress,portNo,provideType, cronData);
            }else{//如果设备已有参数配置，则更新参数配置
              this.updateCronFields(id, boxNo,ipAddress,portNo,provideType, cronData);
            }
          })
          if(results.some(result=>result)){this.$message.success('参数配置操作成功');}
      }).catch(error=>{this.$message.error('检查设备时出错:'+error.message);});
    },
    parseToNumber(value) {
      if(typeof value==='string'){return parseInt(value);}
      else if(typeof value==='number'){return value;}
      else {return value;}
    },
    addDeviceAndCron(id, boxNo,ipAddress,portNo,provideType, cronData) {
      addCron({id,boxNo,ipAddress,portNo,provideType,...cronData}).then(() => {
          this.cronBoxNoList.push(id);
          this.cronList.push({ id, ...cronData });
          this.$message.success('参数配置添加成功');
          this.dialogVisible = false;
          this.getList();}).catch(error => {
          if (error.code === 'DUPLICATE_BOXNO') {
            this.updateCronFields(id, boxNo,ipAddress,portNo,provideType, cronData);
          } else {
            this.$message.error('添加设备失败: ' + error.message);
          }
    });},
    updateCronFields(id, boxNo,ipAddress,portNo,provideType, cronData) {
      updateCron({id,boxNo,ipAddress,portNo,provideType,...cronData}).then(() => {
          const index = this.cronList.findIndex(item => item.id === boxNo);
          if (index !== -1) {
            this.cronList[index] = { id, ...cronData };
          }
          this.dialogVisible = false;
          this.getList();
        }).catch(error => {
          this.$message.error('更新参数配置失败: ' + error.message);
        });
    },
    openCronDialog() {
      //this.form={startTime:0,endTime:0,startTimeTwo:0,endTimeTwo:0,startTimeThree:0,endTimeThree:0,startTimeFour:0,endTimeFour:0};
      this.dialogVisible = true;
    },
    openDialog() {
      // 如果没有选择设备，弹出提示
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }
      // 如果选择了多个设备，无论是否有参数配置都允许打开对话框
      if (this.selectedRows.length > 1) {
        this.openCronDialog();
        return;
      }
      // 如果只选择了一设备，检查它是否已有参数配置
      const selectedBoxNo = this.selectedRows[0].id;
      this.checkDeviceHasCron(selectedBoxNo).then(exists => {
        if (exists) {
          this.$message.warning('已选择设备存在参数配置，请修改已有参数配置。');
        } else {
          this.openCronDialog();  // 设备没有参数配置，允许打开对话框
        }
      }).catch(error => {
        this.$message.error('检查设备时出错: ' + error.message);
      });
    },
    handleTurnOn() {
      const selectedRows = this.selectedRows;
      if (selectedRows.length === 0) {this.$message.warning('请选择设备进行操作！');return;}
      const requests = selectedRows.map(row => {
        if (!row.id) {this.$message.error('选中的设备缺少设备编号！');return null;}
        return this.publish({
          arg: true,
          type: 7,
          id: row.id,
          provideType: row.ipAddress,
          lightLevel: row.portNo
        });
      }).filter(request => request !== null);
      Promise.all(requests).then(results => {
          let msgsuccess = "", msgfail = "", jsonArray = [];
          results.forEach(item=>{jsonArray.push(item.data);});
          const result = jsonArray.reduce((acc, obj) => {return { ...acc, ...obj };},{});
          for (const [key, value] of Object.entries(result)) {
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){this.$message.warning('开启成功的设备编号：'+msgsuccrslt+' 开启失败的设备编号：'+msgfailrslt,{duration:15000});}
          if(msgsuccess.length>0&&msgfail.length==0){this.$modal.msgSuccess('开启成功的设备编号：'+msgsuccrslt,{duration:18000});}
          if(msgsuccess.length==0&&msgfail.length>0){this.$message.warning('开启失败的设备编号：'+msgfailrslt,{duration:15000});}
          this.getList();
      }).catch(error => {console.error(error);});
    },
    handleTurnOff() {
      const selectedRows = this.selectedRows;
      if (selectedRows.length === 0) {this.$message.warning('请选择设备进行操作！');return;}
      const requests = selectedRows.map(row => {
        if (!row.id) {this.$message.error('选中的设备缺少设备编号！');return null;}
        return this.publish({
          arg: false,
          type: 8,
          id: row.id,
          provideType: row.ipAddress,
          lightLevel: row.portNo
        });
      }).filter(request => request !== null);
      Promise.all(requests).then(results => {
          let msgsuccess = "", msgfail = "", jsonArray = [];
          results.forEach(item=>{jsonArray.push(item.data);});
          const result = jsonArray.reduce((acc, obj) => {return { ...acc, ...obj };},{});
          for (const [key, value] of Object.entries(result)) {
              if(value){
                msgsuccess+=key+",";
              }else{
                msgfail+=key+",";
              }
          }
          const msgsuccrslt = msgsuccess.substring(0,msgsuccess.length-1);
          const msgfailrslt = msgfail.substring(0,msgfail.length-1);
          if(msgsuccess.length>0&&msgfail.length>0){this.$message.warning('关灯成功的设备编号：'+msgsuccrslt+' 关灯失败的设备编号：'+msgfailrslt,{duration:15000});}
          if(msgsuccess.length>0&&msgfail.length==0){this.$modal.msgSuccess('关灯成功的设备编号：'+msgsuccrslt,{duration:18000});}
          if(msgsuccess.length==0&&msgfail.length>0){this.$message.warning('关灯失败的设备编号：'+msgfailrslt,{duration:15000});}
          this.getList();
      }).catch(error => {console.error(error);});
    },
    publish(snThing) {
      console.log('发送的数据:', JSON.stringify(snThing));
      return request({
        url: '/mqtt/backclient/publishsunny',
        method: 'post',
        data: snThing,
        headers: {'Content-Type': 'application/json'}
      })
    },
    getStatusImage(status) {// 确保比较的是字符串类型
      return status==='1'?require('@/assets/bigScreen/img/light_on.png'):require('@/assets/bigScreen/img/light_off.png');
    },
    getStateImags(status) {
      return status==='1'?require('@/assets/bigScreen/img/wifion.png'):require('@/assets/bigScreen/img/wifi.png');
    },
    startPolling() {// 每10分钟秒轮询一次数据
      this.pollInterval = setInterval(this.getList, 600000);},
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        console.log(`Selected ID: ${selectedId}, nickName: ${selectedOption.nickName}`);
        this.form.customerId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        console.log('Selected Project Name:', selectedOption.projectname);
        this.form.projectId = selectedOption.id;
      } else {console.error('No matching data found for value:', value);}
    },
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
          console.log("获取用户列表数据", this.options);
        }
      } catch (error) {console.error('获取用户列表失败', error);}
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
          console.log("获取项目名称", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    getList() {
      this.loading = true;
      listSunlight(this.queryParams).then(response => {
        this.sunlightList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancelForDetail() {
      this.dialogVisibleForStrategy = false;
      this.reset();
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        startTime: null,
        endTime: null,
        startTimeTwo: null,
        endTimeTwo: null,
        startTimeThree: null,
        endTimeThree: null,
        startTimeFour: null,
        endTimeFour: null,
        id: null,
        adminId: null,
        customerId: null,
        projectId: null,
        devName: null,
        ipAddress: null,
        portNo: null,
        lightStatus: "0",
        lightAdjustLevel: null,
        lightVolt: null,
        lightCurrent: null,
        activePower: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selectedRows = selection;
      this.sunlightList.forEach(row => {
        row.checked = selection.some(item => item.id === row.id);
      });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSunlight(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSunlight(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("修改失败", error);
              this.$modal.msgError("修改失败");});
          } else {
            addSunlight(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess("新增成功");
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除慧光智慧太阳能灯编号为"' + ids + '"的数据项？').then(function() {
        return delSunlight(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('iot/sunlight/export', {
        ...this.queryParams
      }, `sunlight_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.strategy-dialog {
  font-family: inherit;
}
.strategy-form {
  padding: 0 10px;
}
.strategy-section {
  margin-bottom: 20px;
  position: relative;
}
.strategy-header {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.strategy-title {
  font-size: 16px;
  color: #4169E1;
  font-weight: 500;
}
.strategy-inputs {
  display: flex;
  margin: 0 !important;
}
.custom-form-item {
  margin-bottom: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
  background-color: #fff;
  transition: all 0.3s ease;
}
.custom-form-item:hover {
  border-color: #409EFF;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}
.custom-form-item >>> .el-input__inner {
  height: 32px;
  line-height: 32px;
}
@media (max-width: 768px) {
  .strategy-dialog {
    width: 90% !important;
  }
  .strategy-inputs {
    flex-direction: column;
  }
  .strategy-inputs .el-col {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>
